﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.ServiceProcess;
using System.Text;

namespace StartProcessAsService
{
    public partial class Service : ServiceBase
    {
        public Service()
        {
            InitializeComponent();
        }

        Process P = null;

        protected override void OnStart(string[] args)
        {
            if (this.P == null)
            {
                this.P = new Process();
                lock (this.P)
                {
                    System.Threading.Thread t = new System.Threading.Thread(
                        new System.Threading.ThreadStart(this.StartProgram));
                    t.Start();
                }
            }
            else
            {
                throw new Exception("there already a process created.");
            }
        }

        private void StartProgram()
        {
            ProcessStartInfo psi = new ProcessStartInfo(
                Properties.Settings.Default.ServiceProgram,
                Properties.Settings.Default.ServiceArgument);
            this.P.StartInfo = psi;
            this.P.Start();
            this.P.WaitForExit();
        }

        protected override void OnStop()
        {
            if (this.P != null)
            {
                lock (this.P)
                {
                    this.P.Kill();
                }
            }
        }
    }
}
